package cn.edu.zafu.bigdata.lmr;

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        String hostname = "192.168.16.74";
        int port = 8888;

        try (Socket socket = new Socket(hostname, port);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
             BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {

            System.out.println("Enter messages (leave empty to quit):");
            String userInput;

            // 设置读取超时
            socket.setSoTimeout(10000); // 10秒超时

            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput);
                // 读取服务器的响应
                String serverResponse = in.readLine();
                System.out.println("Server says: " + serverResponse);
                if (userInput.trim().isEmpty()) {
                    break;
                }
            }
        } catch (UnknownHostException e) {
            System.err.println("Host " + hostname + " not found.");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("I/O error occurred when connecting to " + hostname);
            e.printStackTrace();
        } finally {
            System.out.println("Connection closed.");
        }
    }
}